package bean.converter;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import eao.EaoMeasure;
import entity.Measure;

@ManagedBean
@RequestScoped
public class MeasureConverter implements Converter {

    @EJB
    private EaoMeasure eaoMeasure;

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (!(value instanceof Measure) || ((Measure) value).getId() == null) {
        	return null;
        }

        return String.valueOf(((Measure) value).getId());
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        
    	if (value == null || !value.matches("\\d+")) {
            return null;
        }

        Measure measure = eaoMeasure.find(Integer.valueOf(value));

        if (measure == null) {
            throw new ConverterException(new FacesMessage("Unknown Measure ID: " + value));
        }

        return measure;
    }

}